import axios, { AxiosRequestConfig, AxiosPromise } from 'axios';

class API {
    options: AxiosRequestConfig;
    constructor(){
        const url = import.meta.env.VITE_kHttpServer;
        axios.defaults.withCredentials = true
        this.options = {
          method: 'POST',
          baseURL: url,
          timeout: 30000,
          headers: {
            'Content-Type': 'application/json',
            'token': localStorage.getItem("token") ? localStorage.getItem("token")!.toString():"notoken",
          },
          withCredentials: true
        };
        axios.interceptors.response.use(function (response) {
          // 2xx 范围内的状态码都会触发该函数。
          // 对响应数据做点什么
          console.log('response', response);
          if(response.data['code'] == "0") {
            return response;
          }else{
            return Promise.reject(new Error(response.data['message']));
          }
        }, function (error) {
          // 超出 2xx 范围的状态码都会触发该函数。
          // 对响应错误做点什么
          console.log('[axios]interceptors.response', error);
          if(error.code == "ERR_BAD_REQUEST"){
            if(error.response.status == 401){
              console.log('登录态失效');
              setTimeout(() => {
                  location.href="/#/login";
              }, 1500);
              return Promise.reject(new Error('登录态失效,请重新登陆'));
            }
          }
          return Promise.reject(error);
        });
      
    }
    post(url:string, data:any){
        this.options.url = url;
        this.options.data = data;
        this.options.headers = {
          'Content-Type': 'application/json',
          'token': localStorage.getItem("token") ? localStorage.getItem("token")!.toString():"notoken",
        };
        return axios(this.options).then(ret=>{
          return ret.data;
        });
    }

    postForm(url:string, data:any){
        this.options.url = url;
        this.options.data = data;
        this.options.headers = {
          'Content-Type': 'multipart/form-data',
          'token': localStorage.getItem("token") ? localStorage.getItem("token")!.toString():"notoken",
        };
        return axios(this.options).then(ret=>{
          return ret.data;
        });
    }
}

export default new API();